package org.jeecg.chase.modules.merch.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.chase.common.utils.WeChatUtils;
import org.jeecg.chase.modules.entity.AdhShopCategory;
import org.jeecg.chase.modules.service.IAdhShopCategoryService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.chase.modules.merch.entity.AdhMerchUser;
import org.jeecg.chase.modules.merch.entity.AdhMerchInfo;
import org.jeecg.chase.modules.merch.vo.*;
import org.jeecg.chase.modules.merch.service.IAdhMerchInfoService;
import org.jeecg.chase.modules.merch.service.IAdhMerchUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 商家管理
 * @Author: jeecg-boot
 * @Date:   2022-02-10
 * @Version: V1.0
 */
@Api(tags="商家管理")
@RestController
@RequestMapping("/merch/adhMerchInfo")
@Slf4j
public class AdhMerchInfoController {
	@Autowired
	private IAdhMerchInfoService adhMerchInfoService;
	@Autowired
	private IAdhMerchUserService adhMerchUserService;

	 @Autowired
	 private IAdhShopCategoryService adhShopCategoryService;
	 @Value("${wechat.appId}")
	 private String appId;

	 @Value("${wechat.appKey}")
	 private String appKey;

	 @Value("${wechat.shopPage}")
	 private String page;

	 @Value("${jeecg.path.httpUrlPrePath}")
	 private String httpUrlPrePath;
	 /**
	 * 分页列表查询
	 *
	 * @param adhMerchInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商家管理-分页列表查询")
	@ApiOperation(value="商家管理-分页列表查询", notes="商家管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AdhMerchInfo adhMerchInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AdhMerchInfo> queryWrapper = QueryGenerator.initQueryWrapper(adhMerchInfo, req.getParameterMap());
		Page<AdhMerchInfo> page = new Page<AdhMerchInfo>(pageNo, pageSize);
		IPage<AdhMerchInfo> pageList = adhMerchInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param adhMerchInfoPage
	 * @return
	 */
	@AutoLog(value = "商家管理-添加")
	@ApiOperation(value="商家管理-添加", notes="商家管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AdhMerchInfoPage adhMerchInfoPage) {
		AdhMerchInfo adhMerchInfo = new AdhMerchInfo();
		BeanUtils.copyProperties(adhMerchInfoPage, adhMerchInfo);
//		adhMerchInfo.setLongitude(adhMerchInfoPage.getLongitudeAndlatitude().split(",")[0]);
//		adhMerchInfo.setLatitude(adhMerchInfoPage.getLongitudeAndlatitude().split(",")[1]);
		AdhShopCategory cate = adhShopCategoryService.getById(adhMerchInfo.getMerchCategory());
		adhMerchInfo.setMerchCategoryName(cate.getCategoryName());
		//生成qrCode 商家二维码信息

		adhMerchInfoService.saveMain(adhMerchInfo, adhMerchInfoPage.getAdhMerchUserList());
		try{
			String token = WeChatUtils.postToken(appId,appKey);
			if(StringUtils.isNotBlank(adhMerchInfo.getMerchLogo())){
				String fileName = adhMerchInfo.getMerchLogo();
				fileName =  fileName.split("\\/")[0]+"/"+URLEncoder.encode(fileName.split("\\/")[1], "utf-8");
			 	String code = WeChatUtils.generateQrCode("pages/shopPage/shopPage",adhMerchInfo.getId() , token,httpUrlPrePath+ fileName);
				adhMerchInfo.setQrCode(code);
			}else{
				String code = WeChatUtils.generateQrCode("pages/shopPage/shopPage",adhMerchInfo.getId() , token,"");
				adhMerchInfo.setQrCode(code);
			}
			adhMerchInfoService.updateMain(adhMerchInfo, adhMerchInfoPage.getAdhMerchUserList());
		}catch (Exception e){
			e.printStackTrace();
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param adhMerchInfoPage
	 * @return
	 */
	@AutoLog(value = "商家管理-编辑")
	@ApiOperation(value="商家管理-编辑", notes="商家管理-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody AdhMerchInfoPage adhMerchInfoPage) {
		AdhMerchInfo adhMerchInfo = new AdhMerchInfo();
		BeanUtils.copyProperties(adhMerchInfoPage, adhMerchInfo);
//		adhMerchInfo.setLongitude(adhMerchInfoPage.getLongitudeAndlatitude().split(",")[0]);
//		adhMerchInfo.setLatitude(adhMerchInfoPage.getLongitudeAndlatitude().split(",")[1]);
		AdhMerchInfo adhMerchInfoEntity = adhMerchInfoService.getById(adhMerchInfo.getId());
		if(adhMerchInfoEntity==null) {
			return Result.error("未找到对应数据");
		}
		AdhShopCategory cate = adhShopCategoryService.getById(adhMerchInfo.getMerchCategory());
		adhMerchInfo.setMerchCategoryName(cate.getCategoryName());

		try{
			String token = WeChatUtils.postToken(appId,appKey);
			if(StringUtils.isNotBlank(adhMerchInfo.getMerchLogo())){
				String fileName = adhMerchInfo.getMerchLogo();
				fileName =  fileName.split("\\/")[0]+"/"+URLEncoder.encode(fileName.split("\\/")[1], "utf-8");
				String code = WeChatUtils.generateQrCode("pages/shopPage/shopPage",adhMerchInfo.getId() , token,httpUrlPrePath+ fileName);
				adhMerchInfo.setQrCode(code);
			}else{
				String code = WeChatUtils.generateQrCode("pages/shopPage/shopPage",adhMerchInfo.getId() , token,"");
				adhMerchInfo.setQrCode(code);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		adhMerchInfoService.updateMain(adhMerchInfo, adhMerchInfoPage.getAdhMerchUserList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商家管理-通过id删除")
	@ApiOperation(value="商家管理-通过id删除", notes="商家管理-通过id删除")
	@GetMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		adhMerchInfoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商家管理-批量删除")
	@ApiOperation(value="商家管理-批量删除", notes="商家管理-批量删除")
	@GetMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.adhMerchInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商家管理-通过id查询")
	@ApiOperation(value="商家管理-通过id查询", notes="商家管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AdhMerchInfo adhMerchInfo = adhMerchInfoService.getById(id);
		adhMerchInfo.setLongitudeAndlatitude(adhMerchInfo.getLongitude()+","+adhMerchInfo.getLatitude());
		if(adhMerchInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(adhMerchInfo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商家管理员信息通过主表ID查询")
	@ApiOperation(value="商家管理员信息主表ID查询", notes="商家管理员信息-通主表ID查询")
	@GetMapping(value = "/queryAdhMerchUserByMainId")
	public Result<?> queryAdhMerchUserListByMainId(@RequestParam(name="id",required=true) String id) {
		List<AdhMerchUser> adhMerchUserList = adhMerchUserService.selectByMainId(id);
		return Result.OK(adhMerchUserList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param adhMerchInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdhMerchInfo adhMerchInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<AdhMerchInfo> queryWrapper = QueryGenerator.initQueryWrapper(adhMerchInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<AdhMerchInfo> queryList = adhMerchInfoService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<AdhMerchInfo> adhMerchInfoList = new ArrayList<AdhMerchInfo>();
      if(oConvertUtils.isEmpty(selections)) {
          adhMerchInfoList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          adhMerchInfoList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<AdhMerchInfoPage> pageList = new ArrayList<AdhMerchInfoPage>();
      for (AdhMerchInfo main : adhMerchInfoList) {
          AdhMerchInfoPage vo = new AdhMerchInfoPage();
          BeanUtils.copyProperties(main, vo);
          List<AdhMerchUser> adhMerchUserList = adhMerchUserService.selectByMainId(main.getId());
          vo.setAdhMerchUserList(adhMerchUserList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "商家管理列表");
      mv.addObject(NormalExcelConstants.CLASS, AdhMerchInfoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商家管理数据", "导出人:"+sysUser.getRealname(), "商家管理"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<AdhMerchInfoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), AdhMerchInfoPage.class, params);
              for (AdhMerchInfoPage page : list) {
                  AdhMerchInfo po = new AdhMerchInfo();
                  BeanUtils.copyProperties(page, po);
                  adhMerchInfoService.saveMain(po, page.getAdhMerchUserList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
	 @AutoLog(value = "商家管理-列表查询")
	 @ApiOperation(value="商家管理-列表查询", notes="商家管理-列表查询")
	 @GetMapping(value = "/getAllMerchList")
    public Result<?> getAllMerchList(){
		 AdhMerchInfo adhMerchInfo = new AdhMerchInfo();
		 HashMap<String,String[]> param = new HashMap<>();
		 QueryWrapper<AdhMerchInfo> queryWrapper = QueryGenerator.initQueryWrapper(adhMerchInfo, param);
		 List<AdhMerchInfo> queryList = adhMerchInfoService.list(queryWrapper);
		 return Result.OK(queryList);
	 }
}
